import WebSocket from 'ws';
import http from 'http';

type MessageHandle = (data: any) => void;

interface IWebsocketMessage {
  type: 'exec' | string;
  // 指定执行代码的sdk名称，不传会默认全部广播到全部的SDK
  name?: string;
  data: string;
}

class WSS {
  wss: WebSocket.Server;
  receivedHandles: MessageHandle[] = [];

  static instance: WSS;

  constructor(server: http.Server) {
    if (this.wss) {
      return WSS.instance;
    }
    WSS.instance = this;

    this.wss = new WebSocket.Server({
      server,
      path: '/ws',
    });

    this.wss.on('connection', async (ws: WebSocket, request: http.IncomingMessage) => {
      ws.send(JSON.stringify({ msg: 'WebSocket连接已经成功建立了' }));
      ws.on('message', rawData => {
        const data = rawData.toString();
        console.log('\x1B[36m%s\x1B[0m', data);
        this.receivedHandles.forEach(handler => handler(data));
      });
    });
  }

  addReceivedHandle(handler: MessageHandle) {
    this.receivedHandles.push(handler);
  }

  sendData(data: any) {
    if (!(this.wss instanceof WebSocket.Server)) {
      return;
    }

    this.wss.clients.forEach((client: WebSocket) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(data));
      }
    });
  }
}

export default WSS;
